// ignore_for_file: unnecessary_this

import 'package:flutter/material.dart';
import 'package:medical_pro_flutter/api/Api.dart';
import '../../entity/User.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:dio/dio.dart';

import '../dialog/LoadingDialog.dart';
import '../dialog/SuccessDialog.dart';
import '../dialog/FailDialog.dart';

class ChangePWDialog extends Dialog {
  TextEditingController oldPWController = TextEditingController();
  TextEditingController newPWfirstPWController = TextEditingController();
  TextEditingController newPWsecondPWController = TextEditingController();

  bool _obscureTextPassword_old = true;
  bool _obscureTextPassword_new1 = true;
  bool _obscureTextPassword_new2 = true;

  static BuildContext? ctxt;

  @override
  Widget build(BuildContext context) {
    // print('context：$context');
    ctxt = context;
    return Material(
      type: MaterialType.transparency,
      child: Center(
          child: Container(
        height: 450,
        width: 300,
        color: Colors.white,
        child: Column(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(10),
              child: Stack(
                children: <Widget>[
                  Align(
                    alignment: Alignment.centerLeft,
                    child: InkWell(
                      child: const Icon(Icons.vpn_key),
                      onTap: () {
                        Navigator.pop(context);
                      },
                    ),
                  ),
                  const Align(
                    alignment: Alignment.center,
                    child: Text('修改密码'),
                  ),
                  Align(
                    alignment: Alignment.centerRight,
                    child: InkWell(
                      child: const Icon(Icons.close),
                      onTap: () {
                        Navigator.pop(context);
                      },
                    ),
                  ),
                ],
              ),
            ),
            const Divider(),
            Container(
                margin: const EdgeInsets.all(10),
                child: TextField(
                  controller: oldPWController,
                  obscureText: _obscureTextPassword_old,
                  decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: '旧密码',
                    // suffixIcon: GestureDetector(
                    //   onTap: () {
                    //     _obscureTextPassword_old = !_obscureTextPassword_old;
                    //   },
                    //   child: Icon(
                    //     _obscureTextPassword_old
                    //         ? FontAwesomeIcons.eye
                    //         : FontAwesomeIcons.eyeSlash,
                    //     size: 15.0,
                    //     color: Colors.black,
                    //   ),
                    // ),
                  ),
                )),
            const Divider(),
            Container(
                margin: const EdgeInsets.all(10),
                child: TextField(
                  controller: newPWfirstPWController,
                  obscureText: _obscureTextPassword_new1,
                  decoration: const InputDecoration(
                      border: OutlineInputBorder(), labelText: '新密码'),
                )),
            const Divider(),
            Container(
                margin: const EdgeInsets.all(10),
                child: TextField(
                  controller: newPWsecondPWController,
                  obscureText: _obscureTextPassword_new2,
                  decoration: const InputDecoration(
                      border: OutlineInputBorder(), labelText: '确认新密码'),
                )),
            Padding(
              padding: const EdgeInsets.all(10),
              child: Stack(
                children: <Widget>[
                  Align(
                      alignment: Alignment.centerLeft,
                      child: ElevatedButton(
                          child: const Text('确认修改'), onPressed: _submitChange)),
                  Align(
                      alignment: Alignment.centerRight,
                      child: ElevatedButton(
                          style: ButtonStyle(
                              backgroundColor:
                                  MaterialStateProperty.all(Colors.grey)),
                          child: Text('取消'),
                          onPressed: () {
                            Navigator.pop(context);
                          })),
                ],
              ),
            ),
          ],
        ),
      )),
    );
  }

  _submitChange() async {
    late String oldPWTrue = User.password;
    late String oldPWNow = oldPWController.text;
    late String newPWfirst = newPWfirstPWController.text;
    late String newPWsecond = newPWsecondPWController.text;

    if (oldPWNow == '' || newPWfirst == '' || newPWsecond == '') {
      Fluttertoast.showToast(
        msg: '请先完成输入！',
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIosWeb: 3,
        backgroundColor: Colors.white,
        textColor: Colors.black,
        fontSize: 16.0,
      );
      return;
    }

    if (oldPWNow != oldPWTrue) {
      Fluttertoast.showToast(
        msg: '旧密码输入错误！',
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIosWeb: 3,
        backgroundColor: Colors.white,
        textColor: Colors.black,
        fontSize: 16.0,
      );
      return;
    }
    if (newPWfirst != newPWsecond) {
      Fluttertoast.showToast(
        msg: '两次新密码不一致！',
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIosWeb: 3,
        backgroundColor: Colors.white,
        textColor: Colors.black,
        fontSize: 16.0,
      );
      return;
    }
    Navigator.pop(ctxt!);
    String url = API.BASE_URL + API.CHANGE_INFO;
    print('请求的url：$url');

    Response response;

    try {
      showDialog(
          context: ctxt!,
          builder: (BuildContext context) {
            return LoadingDialog(text: '加载中...');
          });

      var dio = Dio();
      var formData = FormData.fromMap({
        'job_num': User.job_num,
        'name': User.name,
        'hospital': User.hospital,
        'password': newPWsecond,
        'phone_num': User.phone_num,
        'type': User.type,
      });
      response = await dio.put(url, data: formData);
      print('code:${response.statusCode}');

      //拿到返回数据，先实例化更改User，再同步到本地数据库
      if (response.statusCode == 200) {
        // Map<String, dynamic> changedInfo = json.decode(response.data);
        Map<String, dynamic> changedInfo =
            Map<String, dynamic>.from(response.data);

        User.password = changedInfo['password'];
        User.updateToLocalDB();

        Navigator.pop(ctxt!);

        showDialog(
            context: ctxt!,
            builder: (BuildContext context) {
              return SuccessDialog(text: '修改成功');
            });
      }
    } catch (e) {
      print(e.toString());
      Navigator.pop(ctxt!);

      showDialog(
          context: ctxt!,
          builder: (BuildContext context) {
            return FailDialog(text: '修改失败');
          });
    }
  }
}
